import sqlite3, datetime
from django.shortcuts import render
from django.http import HttpResponse
from shared_resources import *

def classroom_edit(request, classroom_id):
	initialize(request)
	output = ""
	
	if not request.session["rights"]["edit_classrooms"]:
		output += '<p class="error_message">'+t('You do not have the rights to edit classrooms.')+'</p>'
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    

		result = sql_cursor.execute("""select name from classrooms where id = ?""", (classroom_id,)).fetchone()
		if result == None:
			output += '<div class="col-xs-12"><p class="bg-warning">'+t('Classroom does not exist')+'</p></div>'
		else:
			if 'name' in request.POST.keys():
				values = (request.POST["name"], to_int(classroom_id))
				sql_cursor.execute("""Update classrooms set name = ? where id = ?""", values)
				sql_connection.commit()
				output += '<b>'+t('Room info updated')+'</b><br />'
			
			output += (
			'<form action="?" method="POST">'
			'<table class="newuser">'
			'<tr><td>'+t('Name: ')+'</td><td><input type="text" name="name" value="'+result[0]+'"></td></tr>'
			'<tr><td></td><td><input class="btn btn-primary" type="submit" value="'+t('Edit')+'"></td></tr>'
			'</table>'
			'</form>')
	
	return format_response(version["icons"]["classrooms"]+t("Edit classroom"), output)

def classroom_overview(request):
	initialize(request)
	output = ""
	
	if not request.session["rights"]["view_classrooms"]:
		output += '<p class="error_message">'+t('You do not have the rights to view classrooms.')+'</p>'
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    

		if 'name' in request.POST.keys():
			values = (
				request.POST.get('name', ''),
			)

			sql_cursor.execute("""INSERT INTO classrooms ('name') VALUES (?)""", values)
			sql_connection.commit()
			
			output += '<p class="bg-success">'+t('New classroom added')+'</b>'
		
		if 'delete' in request.POST.keys():
			if not request.session["rights"]["delete_classrooms"]:
				output += '<p class="error_message">'+t('You do not have the rights to delete classrooms.')+'</p>'
			else:
				result = sql_cursor.execute("""select name from classrooms where id = ?""", (request.POST["delete"],)).fetchone()
				log_message(sql_cursor, t('Classroom %s deleted', (result[0])))
				sql_cursor.execute("""delete from classrooms where id = ?""", (request.POST["delete"],))
				sql_cursor.execute("""update lessons set room_id = -1 where room_id = ?""", (to_int(request.POST["delete"]),))
				sql_connection.commit()
				output += '<p class="bg-success">'+t('Classroom %s deleted', (to_str(result[0])))+'</p>'
		
		db_rows = sql_cursor.execute("""SELECT id, name FROM classrooms""")

		output += '<div class="row"><div class="col-xs-12 col-md-6"><h3>'+t('Current Classrooms')+'</h3><table class="viewuser table table-striped table-hover"><tr><th>'+t('Room')+'</th><th></th></tr>'
		
		for row in db_rows:
			output += '<tr><td>'+row[1]+'</td><td style="text-align:right">'
			if request.session["rights"]["edit_classrooms"]:
				output += '<a href="/office/classroom-edit/'+str(row[0])+'/">'+version["icons"]["edit"]+'</a>'
			output += '<a href="/office/classroom-schedule/'+str(row[0])+'/">'+version["icons"]["schedule2"]+'</a>'
			if request.session["rights"]["edit_classrooms"]:
				output += '<a href="#" onclick="confirm_delete(\''+str(row[0])+'\', \''+row[1]+'\')">'+version["icons"]["delete"]+'</a>'
			output += '</td></tr>'
		output += '</table></div>'
		
		
		output += """
		<div class="col-xs-12 col-md-6">
		<h3>"""+t("Create Classroom")+"""</h3>
		<form action="?" method="POST">
		<table class="newuser table">
		<tr><td>"""+t("Name: ")+"""</td><td><input type="text" name="name"></td></tr>
		<tr><td></td><td><input class="btn btn-primary" type="submit" value='"""+t("Create")+"""'></td></tr>
		</table>
		</form>
		<script>
			function confirm_delete(id, name){
				var retVal = confirm('"""+t('Are you sure you want to remove classroom %%s?')+"""'.replace('%s', name));
				if( retVal == true ){
					post_request({"delete": id}, "/office/classroom-overview/");
					return true;
				}
			}
		</script>
		</div>
		</div>

		"""

	return format_response(version["icons"]["classrooms"]+t("Classroom Options"), output)
	
def classroom_schedule(request, classroom_id, selected_week):
	initialize(request)
	output = ""

	sql_connection = sqlite3.connect(global_vars["database"])
	sql_cursor = sql_connection.cursor()    
	
	header = t("Room schedule")
	
	if not request.session["rights"]["view_classrooms"]:
		output += '<p class="error_message">'+t('You do not have the rights to view classrooms.')+'</p>'
	else:
	
		result = sql_cursor.execute("""select name from classrooms where id = ?""", (classroom_id,)).fetchone()
		if result == None:
			output += '<div class="col-xs-12"><p class="bg-warning">'+t('Classroom does not exist')+'</p></div>'
		else:
		
			request.session['schedule_week'] = int(selected_week) if selected_week != None else request.session['schedule_week']
			
			schedule = {0:{},1:{},2:{}}
			
			classes = {}
			lessons = {}
			db_rows = sql_cursor.execute("""select start_time, end_time, (select teacher_id from classes where id = lessons.class_id), id, lessons.room_id, (select subject from classes where id = lessons.class_id), (select first_name from staff where id = (select teacher_id from classes where id = lessons.class_id)), class_id, (select subject from classes where id = class_id), (select description from classes where id = class_id) from lessons where room_id = ? and start_time >= ? and end_time <= ?""", (classroom_id, week_to_stamp(request.session['schedule_week']), week_to_stamp(request.session['schedule_week']+1)))
			for row in db_rows:
				schedule[2][row[3]] = {"id": row[3], "start_time": row[0] - week_to_stamp(request.session['schedule_week']), "end_time": row[1] - week_to_stamp(request.session['schedule_week']), "type": 3, "editable": 1, "layer": -1}
				lessons[row[3]] = {"id":row[3], "room_id":row[4], "subject_id":row[5], "teacher_name":row[6], "class_id":row[7], "can_confirm": False}
				classes[row[7]] = {"description": class_subjects[row[8]]+" - "+row[9]}
				
			for id, value in classes.iteritems():
				student_names = []
				db_rows = sql_cursor.execute("""select (select first_name from students where id = student_id) from student_classes where class_id = ?""", (id,))
				for row in db_rows:
					student_names.append(row[0])
				classes[id]["students"] = ', '.join(student_names[:2]) + ("..." if len(student_names) > 2 else "")
			
			rooms = {classroom_id: {"name": result[0], "unavailable": {}}}
			
			header = t('Schedule for room %s', (result[0]))
			output += schedule_html(0, schedule, "/office/classroom-schedule/"+classroom_id, lessons, rooms, classes)
	
	return format_response(version["icons"]["classrooms"]+header, output)
